package com.tpvlog.drc.server;

import com.tpvlog.drc.common.utils.StringUtils;
import com.tpvlog.drc.server.config.Configuration;
import com.tpvlog.drc.server.config.ConfigurationException;
import com.tpvlog.drc.server.constant.NodeType;
import com.tpvlog.drc.server.node.NodeStatus;
import com.tpvlog.drc.server.node.master.MasterNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class GovernServer {
    private static final Logger LOGGER = LoggerFactory.getLogger(GovernServer.class);

    /**
     * 系统关闭检查的时间间隔
     */
    private static final long SHUTDOWN_CHECK_INTERVAL = 300L;

    public static void main(String[] args) {
        try {
            LOGGER.info("starting govern server......");

            // 1.初始化节点状态
            NodeStatus.getInstance().setStatus(NodeStatus.INITIALIZING);

            // 2.解析配置文件
            String configPath = args[0];
            if (StringUtils.isEmpty(configPath)) {
                throw new ConfigurationException("configuration file path cannot be empty......");
            }
            Configuration.getInstance().parse(configPath);

            // 3.启动当前节点
            startNode();

            // 4.更新节点状态
            NodeStatus.getInstance().setStatus(NodeStatus.RUNNING);
            LOGGER.info("node started, it is running now......");

            // 5.主线程Hang on，直到系统退出
            waitForShutdown();
        } catch (ConfigurationException e) {
            LOGGER.error("encounter error when parsing configuration file", e);
            System.exit(2);
        } catch (InterruptedException e) {
            LOGGER.error("encounter thread interrupted error", e);
            System.exit(1);
        } catch (Exception e) {
            LOGGER.error("encounter error", e);
            System.exit(0);
        }
    }

    /**
     * 启动当前这个节点
     */
    private static void startNode() {
        String nodeType = Configuration.getInstance().getNodeType();
        if (NodeType.MASTER.equals(nodeType)) {
            MasterNode masterNode = new MasterNode();
            masterNode.start();
        }
    }

    /**
     * 等待节点被停止
     */
    private static void waitForShutdown() throws InterruptedException {
        while (NodeStatus.RUNNING == NodeStatus.get()) {
            Thread.sleep(SHUTDOWN_CHECK_INTERVAL);
        }
    }
}
